package cn.zn.framework.common.handler;

import cn.hutool.core.util.StrUtil;
import cn.zn.framework.common.utils.R;
import cn.zn.framework.common.utils.Result;
import com.alibaba.fastjson.JSON;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import springfox.documentation.swagger.web.SwaggerResource;

/**
 * <pre>
 * @projectName: finance-all
 * @packageName: cn.zn.framework.common.handler
 * @className: ResponseResultHandler
 * @description: 说明类用途
 * @author: zn
 * @date: 2021/10/19 14:25
 * </pre>
 */
@RestControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o == null) {
            return R.ok();
        }
        String path = serverHttpRequest.getURI().getPath();
        if (StrUtil.contains(path, "swagger-resources") ||
                StrUtil.contains(path, "api-docs")) {
            return o;
        }
        if (o instanceof Result) {
            return o;
        }
        if (o instanceof R) {
            return o;
        }
        if (o instanceof String) {
            return JSON.toJSONString(R.ok().put("data", o));
        }
        return R.ok().put("data", o);
    }
}
